package com.gao.weblog.web.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gao.weblog.common.domain.dos.ArticleDO;
import com.gao.weblog.common.domain.mapper.ArticleMapper;
import com.gao.weblog.common.model.dto.ArticleQueryDTO;
import com.gao.weblog.common.utils.PageResponse;
import com.gao.weblog.common.utils.Response;
import com.gao.weblog.web.convert.ArticleConvert;
import com.gao.weblog.web.module.vo.archive.FindArchiveArticlePageListReqVO;
import com.gao.weblog.web.module.vo.archive.FindArchiveArticlePageListRspVO;
import com.gao.weblog.web.module.vo.archive.FindArchiveArticleRspVO;
import com.gao.weblog.web.service.ArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;


@Service
public class ArchiveServiceImpl implements ArchiveService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Response findArchivePageList(FindArchiveArticlePageListReqVO findArchiveArticlePageListReqVO) {
        Long current = findArchiveArticlePageListReqVO.getCurrent();
        Long size = findArchiveArticlePageListReqVO.getSize();
        ArticleQueryDTO articleQueryDTO = new ArticleQueryDTO();
        articleQueryDTO.setCurrent(current);
        articleQueryDTO.setSize(size);
        Page<ArticleDO> page = articleMapper.selectPageList(articleQueryDTO);
        List<ArticleDO> articleDOS = page.getRecords();

        List<FindArchiveArticlePageListRspVO> vos = new ArrayList<>();

        if (!CollectionUtils.isEmpty(articleDOS)) {
            List<FindArchiveArticleRspVO> archiveArticleRspVOS = articleDOS.stream()
                    .map(articleDO -> ArticleConvert.INSTANCE.convertDO2ArchiveRspVO(articleDO))
                    .collect(Collectors.toList());

            Map<YearMonth, List<FindArchiveArticleRspVO>> map = archiveArticleRspVOS.stream()
                    .collect(Collectors.groupingBy(FindArchiveArticleRspVO::getCreateMonth));

            Map<YearMonth, List<FindArchiveArticleRspVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(map);

            sortedMap.forEach((k,v) ->
                    vos.add(FindArchiveArticlePageListRspVO.builder()
                            .month(k)
                            .articles(v)
                            .build()));
        }
        return PageResponse.success(page, vos);
    }
}
